package com.android.fitcontrol;

/**
 * @author yzhadan
 * main activity with list of exersices
 */
import java.util.ArrayList;
import java.util.Date;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.fitcontrol.bean.Exercise;
import com.android.fitcontrol.database.DBConnector;

public class ExerciseListActivity extends Activity implements ActionBar.OnNavigationListener {
	
	private static final int TODAY_EXERCISE = 0;
	private static final int WEEK_EXERCISE = 1;
	public static final int IDM_DELETE = 101;
	
	private ListView mExersiceList;
	private DBConnector connector;
	private Cursor cursor;
	private ExerciseListAdapter mExercise;
	private Button mAddExerciseButton;
	
	private int training_id; // should be initialized from intent!!!!
	private String selection;
	private String [] arg;

	
	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.main);
		
		training_id = getIntent().getExtras().getInt("training_id");
		//expression to query records
		selection = Exercise.TRAINING_ID + " = ?";
		arg = new String [] {String.valueOf(training_id)};
		
		SpinnerAdapter actionBarSpinnerAdapter = ArrayAdapter
				.createFromResource(this, R.array.activity_array,
						android.R.layout.simple_spinner_dropdown_item);
		
		//@dmalets action bar
		ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		actionBar.setListNavigationCallbacks(actionBarSpinnerAdapter, this);
		
		actionBar.setDisplayShowCustomEnabled(true);
		
		long date = getIntent().getLongExtra("pickedDate", 0);
		String showDate = "Not avaliable";
		if (date != 0) {
			Date d = new Date(getIntent().getLongExtra("pickedDate", 0));
			showDate = d.getDate() + "." + (d.getMonth() + 1) + "."
					+ (1900 + d.getYear());
		}
		TextView currentDate = new TextView(this);
		currentDate.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
		currentDate.setText(showDate);
		actionBar.setCustomView(currentDate);
		//

		connector = new DBConnector(this);
		mExersiceList = (ListView) findViewById(R.id.exersiceList);
		mAddExerciseButton = (Button) findViewById(R.id.add_new_exercise_button);

		cursor = connector.query(Exercise.TABLE_NAME, null, selection, arg, null,
				null, null);
		mExercise = new ExerciseListAdapter(this,
				R.layout.exersice_list_layout, cursor, new String[] {
						Exercise.ICON, Exercise.EXERCISE_NAME }, new int[] {
						R.id.exersiceImg, R.id.exersiceName });
		mExersiceList.setAdapter(mExercise);
		registerForContextMenu(mExersiceList);
		mExersiceList
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long id) {
						// TODO Auto-generated method stub
						Intent intent = new Intent();
						intent.setClass(ExerciseListActivity.this, ExerciseDetailActivity.class);
						intent.putExtra(Exercise._ID, String.valueOf(id));
						startActivity(intent);
					}
				});
		mAddExerciseButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(5);
			}
		});
		cursor.close();
		connector.close();
	}
	
	@Override
	public void onResume() {
		super.onResume();
		connector = new DBConnector(this);

		cursor = connector.query(Exercise.TABLE_NAME, null, selection, arg, null,
				null, null);
		mExercise = new ExerciseListAdapter(this,
				R.layout.exersice_list_layout, cursor, new String[] {
						Exercise.ICON, Exercise.EXERCISE_NAME }, new int[] {
						R.id.exersiceImg, R.id.exersiceName });
		
		mExersiceList.setAdapter(mExercise);
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		cursor.close();
		connector.close();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		getMenuInflater().inflate(R.menu.main_menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case R.id.action_bar_logout_item:
			connector.delete("user", -1);
			connector.close();
			Intent loginIntent = new Intent(this, LoginActivity.class);
			loginIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
			startActivity(loginIntent);
			finish();
			break;
		case R.id.action_bar_calendar_item:
			Intent monthScheduleIntent = new Intent(this, MonthScheduleActivity.class);
			//monthScheduleIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
			startActivity(monthScheduleIntent);
			//finish();
		}
		return true;
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		connector.close();
		cursor.close();
	}


	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		
		switch (itemPosition) {
		case TODAY_EXERCISE:
			//check training
//			Intent exerciseListIntent = new Intent(ExerciseListActivity.this, ExerciseListActivity.class);
//			exerciseListIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//			Format formatter = new SimpleDateFormat("dd-mm-yy");
//			Calendar calendar = new GregorianCalendar();
//			String dat = calendar.get(Calendar.DAY_OF_MONTH) + "-" + calendar.get(Calendar.MONTH) + "-" + calendar.get(Calendar.YEAR);
//			Date resultDate = new Date();
//			try{
//				resultDate = (Date) formatter.parseObject(dat);
//			}catch(Exception e){
//				e.printStackTrace();
//			}
//			exerciseListIntent.putExtra("pickedDate", resultDate.getTime());
//			String where = Training.USER_ID + " = ? and " + Training.DATE + " = ?";
//			String [] args = new String[]{String.valueOf(CommonUtils.getUserId()), String.valueOf(resultDate.getTime())};
//			Cursor cur = connector.query(Training.TABLE_NAME, null, where, args, null, null, null);
//			boolean isExistTraining = false;
//			if(cur.moveToFirst()){
//				isExistTraining = true;
//				exerciseListIntent.putExtra("training_id", cur.getInt(Training.NUM_ID));
//				startActivity(exerciseListIntent);
//			}
//			else{
//				Intent calendarIntent = new Intent(ExerciseListActivity.this, MonthScheduleActivity.class);
//				calendarIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//				startActivity(calendarIntent);
//			}
//			cur.close();
			break;
		case WEEK_EXERCISE :
			Intent weekIntent = new Intent(this, ScheduleWeekActivity.class);
			//weekIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(weekIntent);
			break;
		default:
			throw new IllegalArgumentException("Unknown spinner position : "
					+ itemId);
		}
		return true;
	}
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		if(v.getId() == R.id.exersiceList){ 
			menu.add(Menu.NONE, IDM_DELETE, Menu.NONE, getResources().getString(R.string.context_menu_delete));
		}
	}
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
		if(item.getItemId() == IDM_DELETE)
		{
			int exercise_id = (int)mExercise.getItemId(info.position);
			connector.delete(Exercise.TABLE_NAME, exercise_id);
			cursor = connector.query(Exercise.TABLE_NAME, null, selection, arg, null,
					null, null);
			mExercise.changeCursor(cursor);
			if(cursor.moveToFirst()){
				mExersiceList.setSelection(0);
			}
			return true;
		}
		else{
			return super.onContextItemSelected(item);
		}
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		LayoutInflater inflater = getLayoutInflater();
		View layout = inflater.inflate(R.layout.dialog,
				(ViewGroup) findViewById(R.id.dialog_root));
		final AutoCompleteTextView autoText = (AutoCompleteTextView) layout
				.findViewById(R.id.exercise_auto_complete);
		final Cursor c = connector.query(Exercise.TABLE_NAME, new String[]{Exercise.EXERCISE_NAME, Exercise.ICON}, null, null, null,
				null, null);
		final ArrayList<String> existingExercises = makeArrayFromCursor(c);
		final ArrayList<Integer> existingExercisesIcons = makeIconArrayFromCursor(c);
		c.close();
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, existingExercises);
		autoText.setAdapter(adapter);
		AlertDialog.Builder builder = new AlertDialog.Builder(ExerciseListActivity.this);
		builder.setView(layout);
		builder.setTitle(getResources().getString(R.string.dialog_title));
		builder.setPositiveButton(
				getResources().getString(
						R.string.dialog_positive_button),
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog,
							int which) {
						// TODO Auto-generated method stub
						String exName = autoText.getText().toString();
						if(exName.length() < 1){
							Toast.makeText(ExerciseListActivity.this, getResources().getString(
									R.string.dialog_error), 3).show();
						}
						else{
							Exercise ex = new Exercise();
							ex.setExerciseName(exName);
							ex.setIcon(R.drawable.ic_launcher);
							ex.setTraining_ID(training_id);
							if(existingExercises.size() > 0){
								for(int i=0; i<existingExercises.size(); i++){
									if(existingExercises.get(i).equals(exName)){
										ex.setIcon(existingExercisesIcons.get(i));
										break;
									}
								}
							}
							connector.insert(ex);
							cursor = connector.query(Exercise.TABLE_NAME, null, selection, arg, null,
									null, null);
							mExercise = new ExerciseListAdapter(ExerciseListActivity.this,
									R.layout.exersice_list_layout, cursor, new String[] {
											Exercise.ICON, Exercise.EXERCISE_NAME }, new int[] {
											R.id.exersiceImg, R.id.exersiceName });
							
							mExersiceList.setAdapter(mExercise);
							mExersiceList.setSelection(cursor.getCount()-1);
							Toast.makeText(ExerciseListActivity.this, getResources().getString(
									R.string.dialog_save), 3).show();
						}
						
					}
				});
		builder.setNegativeButton(
				getResources().getString(
						R.string.dialog_negative_button),
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog,
							int which) {
						dialog.cancel();
					}
				});
		return builder.create();
	}
	
	private ArrayList<String> makeArrayFromCursor(Cursor c){
		ArrayList<String> list = new ArrayList<String>();
		if(c.moveToFirst()){
			list.add(c.getString(0));
		}
		while(c.moveToNext()){
			list.add(c.getString(0));
		}
		return list;
	}
	
	private ArrayList<Integer> makeIconArrayFromCursor(Cursor c){
		ArrayList<Integer> list = new ArrayList<Integer>();
		if(c.moveToFirst()){
			list.add(c.getInt(1));
		}
		while(c.moveToNext()){
			list.add(c.getInt(1));
		}
		return list;
	}
}
